package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.salesmanage.util.BranchDaySett_Obj;
import com.turing.post.salesmanage.util.SaleOrderPaidDetail;
import com.turing.post.salesmanage.util.SaleOrderPaidDetailDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

/**
 * @author zxp
 * @Dec 23, 2012
 */

@Stateless(mappedName = "salesmanage.impl.SaleOrderPaidDetailDaoImpl")
@Remote
@Local
public class SaleOrderPaidDetailDaoImpl implements SaleOrderPaidDetailDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@Override
	public SaleOrderPaidDetail getSaleOrderPaidDetailBySaleOrderPaidId(
			BigInteger saleOrderPaidId) {
		return _em.find(SaleOrderPaidDetail.class, saleOrderPaidId);
	}

	@Override
	public SaleOrderPaidDetail getSaleOrderPaidDetailForUpdate(
			BigInteger saleOrderPaidId) {
		String sql = "select * from SaleOrderPaidDetail t where t.SaleOrderPaidId="
				+ saleOrderPaidId + " for update";
		Query query = _em.createNativeQuery(sql, SaleOrderPaidDetail.class);
		return (SaleOrderPaidDetail) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SaleOrderPaidDetail> getSaleOrderPaidDetailListBySaleOrderId(
			BigInteger saleOrderId) {
		String sql = "select * from SaleOrderPaidDetail t where t.SaleOrderId = ?1";
		Query query = _em.createNativeQuery(sql, SaleOrderPaidDetail.class);
		query.setParameter(1, saleOrderId);
		return query.getResultList();
	}

	@Override
	public void insertSaleOrderPaidDetail(
			SaleOrderPaidDetail saleOrderPaidDetail)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, saleOrderPaidDetail);
	}

	@Override
	public void updateSaleOrderPaidDetail(
			SaleOrderPaidDetail saleOrderPaidDetail)
			throws PCPSApplicationException {
		GeneralDao.update(_em, saleOrderPaidDetail);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SaleOrderPaidDetail> getSaleOrderPaidDetailListByCondition(
			BigInteger saleOrderId, String paidType, String startTranTime,
			String endTranTime, BigInteger startPaidAmount,
			BigInteger endPaidAmount, String paidClass, Integer page) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		String sql = "select t.* from SaleOrderPaidDetail t where t.saleOrderId=?1 and (?2 is null or paidType=?2) and "
				+ "(?3 is null or TranTime>=to_date(?3,'yyyy-mm-dd hh24:mi:ss')) and "
				+ "(?4 is null or TranTime<=to_date(?4,'yyyy-mm-dd hh24:mi:ss')) and (?5 is null or PaidAmount>=to_number(?5)) and "
				+ "(?6 is null or PaidAmount<=to_number(?6)) and (?7 is null or paidClass=?7) order by tranTime desc";
		Query query = null;
		if (page == -1){
			query = _em.createNativeQuery(sql, SaleOrderPaidDetail.class);
		}else{
			query = _em.createNativeQuery(sql, SaleOrderPaidDetail.class)
					.setFirstResult(startPosition).setMaxResults(maxResult);
		}
		
		query.setParameter(1, saleOrderId);
		query.setParameter(2, paidType);
		// 起始时间
		if (PCPSUtil.isEmpty(startTranTime)) {
			query.setParameter(3, "");
		} else {
			query.setParameter(3, startTranTime + " 00:00:00");
		}
		// 终止时间
		if (PCPSUtil.isEmpty(endTranTime)) {
			query.setParameter(4, "");
		} else {
			query.setParameter(4, startTranTime + " 23:59:59");
		}
		query.setParameter(5, startPaidAmount);
		query.setParameter(6, endPaidAmount);
		query.setParameter(7, paidClass);
		List<SaleOrderPaidDetail> paidList = query.getResultList();
		List<SaleOrderPaidDetail> returnList = new ArrayList<SaleOrderPaidDetail>();
		for (SaleOrderPaidDetail sopd : paidList) {
			if (sopd.getCancelSaleOrderPaidId() == null) {
				sopd.setCancelBtn("PaidOffCanceled");
				returnList.add(sopd);
			} else {
				sopd.setCancelBtn("");
				returnList.add(sopd);
			}
		}
		return returnList;
	}

	@Override
	public BigInteger getSaleOrderPaidDetailTotalByCondition(
			BigInteger saleOrderId, String paidType, String startTranTime,
			String endTranTime, BigInteger startPaidAmount,
			BigInteger endPaidAmount, String paidClass) {
		String sql = "select nvl(count(*),0) from SaleOrderPaidDetail t where t.saleOrderId=?1 and (?2 is null or paidType=?2) and "
				+ "(?3 is null or TranTime>=to_date(?3,'yyyy-mm-dd hh24:mi:ss')) and "
				+ "(?4 is null or TranTime<=to_date(?4,'yyyy-mm-dd hh24:mi:ss')) and (?5 is null or PaidAmount>=to_number(?5)) and "
				+ "(?6 is null or PaidAmount<=to_number(?6)) and (?7 is null or paidClass=?7)";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, saleOrderId);
		query.setParameter(2, paidType);
		// 起始时间
		if (PCPSUtil.isEmpty(startTranTime)) {
			query.setParameter(3, "");
		} else {
			query.setParameter(3, startTranTime + " 00:00:00");
		}
		// 终止时间
		if (PCPSUtil.isEmpty(endTranTime)) {
			query.setParameter(4, "");
		} else {
			query.setParameter(4, startTranTime + " 23:59:59");
		}
		query.setParameter(5, startPaidAmount);
		query.setParameter(6, endPaidAmount);
		query.setParameter(7, paidClass);

		return new BigInteger(query.getSingleResult().toString());
	}

	private BigInteger getValue(Object[] o, int idx) {
		if (o == null || idx < 0 || idx > o.length || o[idx] == null)
			return BigInteger.ZERO;

		return new BigInteger(o[idx].toString());
	}

	@SuppressWarnings("unchecked")
	private BranchDaySett_Obj getBranchDaySettByBranchNoAndTranDate(
			String saleBranchNo, Date tranDate, String sql, String dsql,
			String creditSql) {
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, saleBranchNo);
		query.setParameter(2, tranDate);
		List<Object[]> slist = query.getResultList();
		if (slist == null || slist.isEmpty()) {
			slist = new ArrayList<Object[]>();
			slist.add(new Object[] { "0", "0" });
		}
		Object[] sobj = slist.get(0);

		Query dquery = _em.createNativeQuery(dsql);
		dquery.setParameter(1, saleBranchNo);
		dquery.setParameter(2, tranDate);
		List<Object[]> dlist = dquery.getResultList();
		if (dlist == null || dlist.isEmpty()) {
			dlist = new ArrayList<Object[]>();
			dlist.add(new Object[] { "0", "0", "0", "0", "0", "0" });
		}
		Object[] dobj = dlist.get(0);

		Query creditquery = _em.createNativeQuery(creditSql);
		creditquery.setParameter(1, saleBranchNo);
		creditquery.setParameter(2, tranDate);
		List<Object[]> creditlist = creditquery.getResultList();
		if (creditlist == null || creditlist.isEmpty()) {
			creditlist = new ArrayList<Object[]>();
			creditlist.add(new Object[] { "0", "0", "0", "0" });
		}
		Object[] cobj = creditlist.get(0);
		BigInteger credit_discount_fee = getValue(cobj, 2).subtract(
				getValue(cobj, 3));

		BranchDaySett_Obj bds = new BranchDaySett_Obj();
		bds.setSaleBranchNo(saleBranchNo);
		bds.setTranDate(tranDate);
		bds.setTranCount(getValue(sobj, 0).add(getValue(cobj, 0)));
		bds.setCashAmount(getValue(dobj, 0));
		bds.setChequeAmount(getValue(dobj, 1));
		bds.setTranAmount(getValue(dobj, 2));
		bds.setCreditAmount(getValue(cobj, 1));
		bds.setCashFee(getValue(dobj, 3));
		bds.setChequeFee(getValue(dobj, 4));
		bds.setTranFee(getValue(dobj, 5));
		bds.setCreditFee(getValue(cobj, 3));
		bds.setCardFee(BigInteger.ZERO);
		bds.setDiscountFee(getValue(sobj, 1).add(credit_discount_fee));

		return bds;
	}

	/**
	 * 产生某发卡商某机构某日销售日结数据
	 * 
	 * @param issueCompanyNo
	 * @param saleBranchNo
	 * @param tranDate
	 * @return
	 */
	public List<BranchDaySett_Obj> getBranchDaySettByBranchNoAndTranDate(
			String saleBranchNo, Date tranDate) {
		final String sale_sql = "select count(distinct s.SaleOrderId), sum(s.Fee - s.FactFee) from SaleOrder s where s.SaleBranchNo = ?1 and s.TranDate = ?2 and s.PaidType = '0' ";
		final String sale_credit_sql = "select count(distinct s.SaleOrderId), sum(s.TotalSaleAmount), sum(s.Fee), sum(s.FactFee) from SaleOrder s where s.SaleBranchNo = ?1 and s.TranDate = ?2 and s.PaidType = '1' ";
		final String sale_csql = "select count(distinct s.SaleOrderId), sum(s.Fee - s.FactFee) from SaleOrder s where s.SaleBranchNo = ?1 and s.CancelDate = ?2 and s.PaidType = '0' ";
		final String sale_credit_csql = "select count(distinct s.SaleOrderId), sum(s.TotalSaleAmount), sum(s.Fee), sum(s.FactFee) from SaleOrder s where s.SaleBranchNo = ?1 and s.CancelDate = ?2 and s.PaidType = '1' ";
		final String sale_paid_sql = "select count(distinct p.SaleOrderId), 0 from SaleOrderPaidDetail p, SaleOrder s where p.TranDate = ?2 and p.SaleOrderId = s.SaleOrderId and s.SaleBranchNo = ?1 and s.PaidType = '1' ";
		final String sale_dual_csql = "select 0, 0, 0, 0 from DUAL where ?1 = ?1 and ?2 = ?2 ";
		final String sum_sql = "sum( case when p.PaidType = '0' and p.PaidClass = '0' then p.PaidAmount else 0 end), " // 现金销售额
				+ "sum( case when p.PaidType = '1' and p.PaidClass = '0' then p.PaidAmount else 0 end), " // 支票销售额
				+ "sum( case when p.PaidType = '2' and p.PaidClass = '0' then p.PaidAmount else 0 end), " // 转账销售额
				+ "sum( case when p.PaidType = '0' and p.PaidClass = '1' then p.PaidAmount else 0 end), " // 现金手续费
				+ "sum( case when p.PaidType = '1' and p.PaidClass = '1' then p.PaidAmount else 0 end), " // 支票手续费
				+ "sum( case when p.PaidType = '2' and p.PaidClass = '1' then p.PaidAmount else 0 end) " // 转账手续费
		;
		final String sql = "select "
				+ sum_sql
				+ "from SaleOrderPaidDetail p, SaleOrder s "
				+ "where p.TranDate = ?2 and p.PaidAmount > 0 and p.SaleOrderId = s.SaleOrderId and s.SaleBranchNo = ?1 and s.TranDate = ?2 and s.PaidType = '0' ";
		final String csql = "select "
				+ sum_sql
				+ "from SaleOrderPaidDetail p, SaleOrder s "
				+ "where p.TranDate = ?2 and p.PaidAmount < 0 and p.SaleOrderId = s.SaleOrderId and s.SaleBranchNo = ?1 and s.CancelDate = ?2 and s.PaidType = '0' ";
		BranchDaySett_Obj bds_normal = getBranchDaySettByBranchNoAndTranDate(
				saleBranchNo, tranDate, sale_sql, sql, sale_credit_sql);
		bds_normal.setTranType(BranchDaySett_Obj.TRANTYPE_SALE);
		BranchDaySett_Obj bds_cancel = getBranchDaySettByBranchNoAndTranDate(
				saleBranchNo, tranDate, sale_csql, csql, sale_credit_csql);
		bds_cancel.setTranType(BranchDaySett_Obj.TRANTYPE_SALE_CANCEL);

		List<BranchDaySett_Obj> bdslist = new ArrayList<BranchDaySett_Obj>();

		if (!bds_normal.isAllZero())
			bdslist.add(bds_normal);

		if (!bds_cancel.isAllZero())
			bdslist.add(bds_cancel);

		final String psql = "select "
			+ sum_sql
			+ "from SaleOrderPaidDetail p, SaleOrder s "
			+ "where p.TranDate = ?2 and p.SaleOrderId = s.SaleOrderId and s.SaleBranchNo = ?1 and s.PaidType = '1' ";

		BranchDaySett_Obj bds_credit = getBranchDaySettByBranchNoAndTranDate(
				saleBranchNo, tranDate, sale_paid_sql, psql, sale_dual_csql);
		bds_credit.setTranType(BranchDaySett_Obj.TRANTYPE_CREDIT);

		if (!bds_credit.isAllZero())
			bdslist.add(bds_credit);

		return bdslist;
	}

	@Override
	public BigInteger getAlreayPaidAmountBySaleOrderId(BigInteger saleOrderId,
			String paidClass) {
		String sql = "select nvl(sum(t.paidamount),0)"
				+ " from saleorderpaiddetail t "
				+ " where t.saleorderid=?1 and t.paidclass = ?2";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, saleOrderId);
		query.setParameter(2, paidClass);
		return new BigInteger(query.getSingleResult().toString());
	}

}
